﻿#include <QTcpSocket>
#include <QDateTime>
#include <QTimer>
#include "CIsapiServer.h"
#include "CGlobal.h"

CIsapiServer::CIsapiServer()
{

}

CIsapiServer::~CIsapiServer()
{

}

void CIsapiServer::setNetworkParameter(QString sIp, int nPort)
{
	m_sIp = sIp;
	m_nPort = nPort;
}

bool CIsapiServer::startServer(QString &sErrMsg)
{
	if (!this->listen(QHostAddress("0.0.0.0"), m_nPort))
	{
		sErrMsg = A2T("开启监听失败");
		return false;
	}
	else
	{
		return true;
	}
}

void CIsapiServer::incomingConnection(qintptr socketDescriptor)
{
	// 当有新的连接时，创建一个套接字来处理它
	QTcpSocket *socket = new QTcpSocket(this);
	socket->setSocketDescriptor(socketDescriptor);

	// 为每个连接创建缓冲区
	m_requestBuffers[socket] = QByteArray();
	m_requestTimers[socket] = new QTimer(this);
	m_requestTimers[socket]->setSingleShot(true);
	m_requestTimers[socket]->start(30000); // 30秒超时

	connect(socket, &QTcpSocket::readyRead, this, &CIsapiServer::onReadyRead);
	connect(socket, &QTcpSocket::disconnected, this, &CIsapiServer::onDisconnected);
	connect(m_requestTimers[socket], &QTimer::timeout, this, &CIsapiServer::onRequestTimeout);
}

void CIsapiServer::onReadyRead()
{
	QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
	if (!socket) return;

	// 重置超时计时器
	if (m_requestTimers.contains(socket)) {
		m_requestTimers[socket]->start(30000);
	}

	// 读取数据并追加到缓冲区
	QByteArray newData = socket->readAll();
	m_requestBuffers[socket].append(newData);

	qDebug() << A2T("接收到数据: ") << newData.size() << A2T("字节");
	qDebug() << A2T("当前缓冲区大小: ") << m_requestBuffers[socket].size() << A2T("字节");

	// 检查请求是否完整
	if (isRequestComplete(m_requestBuffers[socket])) {
		processCompleteRequest(socket);
	}
}

bool CIsapiServer::isRequestComplete(const QByteArray &requestData)
{
	// 简单的HTTP请求完整性检查
	if (requestData.isEmpty()) {
		return false;
	}

	// 检查是否有完整的请求头
	int headerEnd = requestData.indexOf("\r\n\r\n");
	if (headerEnd == -1) {
		return false; // 请求头还不完整
	}

	// 解析Content-Length
	QByteArray headers = requestData.left(headerEnd);
	QList<QByteArray> headerLines = headers.split('\n');

	int contentLength = 0;
	for (const QByteArray &line : headerLines) {
		if (line.startsWith("Content-Length:")) {
			QByteArray value = line.mid(15).trimmed();
			contentLength = value.toInt();
			break;
		}
	}

	// 计算请求体开始位置
	int bodyStart = headerEnd + 4; // \r\n\r\n 的长度

	// 如果有Content-Length，检查请求体是否完整
	if (contentLength > 0) {
		int bodyReceived = requestData.size() - bodyStart;
		return bodyReceived >= contentLength;
	}

	// 如果没有Content-Length，认为请求头结束就是完整请求
	return true;
}

void CIsapiServer::processCompleteRequest(QTcpSocket *socket)
{
	if (!socket || !m_requestBuffers.contains(socket)) {
		return;
	}

	QByteArray requestData = m_requestBuffers[socket];
	QString srequestData = QString::fromUtf8(requestData);
	qDebug() << A2T("完整请求数据: ") << srequestData;

	// 发射信号
	emit sigNewRequest(requestData);

	// 发送响应
	QByteArray responseHeader = "HTTP/1.1 200 OK\r\n" +
		QString("Date: %1\r\n").arg(QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss")).toUtf8() +
		QString("Content-Type: text/plain\r\n").toUtf8() +
		QString("Connection: close\r\n\r\n").toUtf8() +
		QString("Request received: %1 bytes").arg(requestData.size()).toUtf8();

	socket->write(responseHeader);
	socket->flush();

	// 清理连接相关资源
	cleanupConnection(socket);

	// 关闭连接
	socket->disconnectFromHost();
}

void CIsapiServer::onDisconnected()
{
	QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
	cleanupConnection(socket);
}

void CIsapiServer::onRequestTimeout()
{
	QTimer *timer = qobject_cast<QTimer *>(sender());
	QTcpSocket *socket = nullptr;

	// 找到对应的socket
	for (auto it = m_requestTimers.begin(); it != m_requestTimers.end(); ++it) {
		if (it.value() == timer) {
			socket = it.key();
			break;
		}
	}

	if (socket) {
		qDebug() << A2T("请求超时，关闭连接");
		cleanupConnection(socket);
		socket->abort();
	}
}

void CIsapiServer::cleanupConnection(QTcpSocket *socket)
{
	if (!socket) return;

	// 清理缓冲区
	if (m_requestBuffers.contains(socket)) {
		m_requestBuffers.remove(socket);
	}

	// 清理计时器
	if (m_requestTimers.contains(socket)) {
		if (m_requestTimers[socket]) {
			m_requestTimers[socket]->stop();
			m_requestTimers[socket]->deleteLater();
		}
		m_requestTimers.remove(socket);
	}

	// 断开连接
	socket->disconnect();
}